<?php

namespace App\Services\RoomScore;

use App\Enums\RoomEnum;
use App\Models\MainDB\Dating\RoomDatingScore;
use App\Models\MainDB\GiveGift;
use App\Models\MainDB\RoomManager;
use App\Models\MainDB\RoomUserGiftScore;
use App\Models\MainDB\User;
use App\Repositories\Dating\RoomDatingRepository;
use App\Services\Tools\RedisService;
use Illuminate\Support\Facades\DB;

class RoomManagerServer
{
    public function batchUsersRoleMap(int $roomId, array $userIds): array
    {
        if(empty($userIds)){
            return [];
        }
        $managers = $this->managers($roomId);
        $managers = array_column($managers->toArray(), null, "user_id");
        $res = [];
        foreach ($userIds as $userId){
            if(isset($managers[$userId]))
            {
                $res[$userId] = $managers[$userId]["type"];
            }else{
                $res[$userId]=RoomEnum::ROOM_ROLE_TYPE_VISITOR;
                $userInfo=User::query()->where('user_id',$userId)->first();
                //官方
                if($userInfo->role == 2)
                {
                    $res[$userId]=RoomEnum::ROOM_ROLE_TYPE_ORG;
                }
            }
        }
        return $res;
    }

    public function batchUsersScoreMap(int $roomId, array $userIds): array
    {
        if(empty($userIds)){
            return [];
        }
        $query = RoomUserGiftScore::query();
        $query->where("room_id", $roomId);
        $query->whereIn('user_id',$userIds);
        $query->select(['user_id', DB::raw("sum(score) as score")]);
        $query->groupBy(["user_id"]);
        $models = $query->get();
        return array_column($models->toArray(), "score", "user_id");
    }

    public function batchUserSpecialMap(array $userIds): array
    {
        if(empty($userIds)){
            return [];
        }
        sort($userIds);
        $keys = [];
        $redis = new RedisService();
        foreach ($userIds as $userId) {
//            RedisService::userSpecialAll((int)$userId);
            $keys = array_merge($keys, $redis->userSpecialAll((int)$userId));
        }
        $res = [];
        $specials = $redis->mGetKey($keys);

        $index = 0;
        foreach ($userIds as $userId) {
            $nicknameWidget = !empty($specials[$index]) ? json_decode($specials[$index], true) : [];
            $index += 1;

            $nicknameSpecial = !empty($specials[$index]) ? json_decode($specials[$index], true) : [];
            $index += 1;

            $ride = !empty($specials[$index]) ? json_decode($specials[$index], true) : [];
            $index += 1;

            $join = !empty($specials[$index]) ? json_decode($specials[$index], true) : [];
            $index += 1;

            // 私聊与房间聊天特效用一个
            $chat = !empty($specials[$index]) ? json_decode($specials[$index], true) : [];
            $index += 1;

            $chatroom = !empty($specials[$index]) ? json_decode($specials[$index], true) : [];
            $index += 1;

            $wave = !empty($specials[$index]) ? json_decode($specials[$index], true) : [];
            $index += 1;

            $broadcast = !empty($specials[$index]) ? json_decode($specials[$index], true) : [];
            $index += 1;

            $avatar = !empty($specials[$index]) ? $specials[$index] : [];
            $index += 1;

            $res[$userId] = [
                'avatar' => [
                    'material' => $avatar ?: '',
                ],
                'nickname' => [
                    'material' => $nicknameWidget['special'] ?? ($nicknameWidget['picture'] ?? ''),
                ],
                'nickname_special' => [
                    'material' => $nicknameSpecial['special'] ?? '',
                ],
                'ride' => [
                    'material' => $ride['special'] ?? '',
                    'show_type' => $ride['show_type'] ?? 1,
                ],
                'join' => [
                    'color' => $join['special'] ?? '',
                    'material' => $join['picture'] ?? '',
                    'show_type' => $join['show_type'] ?? 1,
                ],
                'chat' => [
                    'material' => $chat['special'] ?? ''
                ],
                'chatroom' => [
                    'material' => $chatroom['special'] ?? ''
                ],
                'wave' => [
                    'material' => $wave['special'] ?? ''
                ],
                'broadcast' => [
                    'material' => $broadcast['special'] ?? ''
                ],
            ];
        }

        return $res;
    }

    public function batchRoomUsersGiveCoinMap(int $roomId, array $userIds): array
    {
        $res = [];
        if(empty($userIds)){
            return $res;
        }

        $query = GiveGift::query();
        $query->where("room_id", $roomId);
        $query->whereIn('user_id',$userIds);
        $query->groupBy(["user_id"]);
        $query->select(["user_id", DB::raw("sum(total_price) as coin")]);
        $models = $query->get();
        if($models->isEmpty()){
            return $res;
        }
        foreach ($models as $model){
            $res[$model->user_id] = $model->coin;
        }
        return $res;
    }

    public function batchRoomUsersTodayGiveCoinMap(int $roomId, array $userIds): array
    {
        $res = [];
        if(empty($userIds)){
            return $res;
        }

        $query = GiveGift::query();
        $query->where("room_id", $roomId);
        $query->whereIn('user_id',$userIds);
        $query->where(["add_time" => [strtotime(date("Y-m-d")) , ">="]]);
        $query->groupBy(["user_id"]);
        $query->select(["user_id", DB::raw("sum(total_price) as coin")]);
        $models = $query->get();
        if($models->isEmpty()){
            return $res;
        }
        foreach ($models as $model){
            $res[$model->user_id] = (int)$model->coin;
        }
        return $res;
    }

    public function managers(int $roomId)
    {
        $query = RoomManager::query();
        $query->where("room_id", $roomId);
        if(isset($params['user_id']) && $params['user_id'])
        {
            $query->where('user_id',$params['user_id']);
        }
        $query->orderBy("type", "desc");
        $query->select(['id', 'room_id', 'user_id', 'type','is_complain','is_want']);
        return $query->get();
    }

    /**
     * 获取情侣房间的麦位心动
     * @throws
     * @throws
     */
    public function batchDatingScoreMap(int $roomId, array $userIds)
    {
        $datingId = RoomDatingRepository::getInstance()->getDatingId($roomId);
        if (empty($userIds) || empty($datingId)) {
            return [];
        }
        $query = RoomDatingScore::query();
        $query->where("room_id", $roomId);
        $query->whereIn("user_id", $userIds);
        $query->where('game_id', $datingId);
        $query->select(['user_id', 'charm_score', 'gender', 'rank_score']);
        return $query->get()->toArray();
    }
}

